<template>
  <div class="warpper">
    <div class="form" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" size="mini" label-width="160px" style="width:85%">
        <el-tag effect="plain">{{formData.uomtype}}</el-tag>
        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="11">
            <el-form-item label="Status" prop="Status" style="width: 460px;margin-left: 31px;">
              <template slot-scope="scope">
                <span>{{ formData.status }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11" style="text-align: right;">
            <el-form-item>
              <template slot-scope="scope">
                <el-button plain v-permission="['uomorders.update']" type="primary" @click="godisable(true)"
                  :disabled="isapproved"
                  v-if="formData.status =='pending' || formData.status =='rejection'">{{isdiable?"Edit":"Cancel Edit"}}</el-button>
                <el-button plain v-permission="['uomorders.void']" type="default" @click="editstatus(id, 'voided')"
                  :disabled="isapproved" v-if="formData.status =='pending' && isdiable">Voided</el-button>
                <el-button plain v-permission="['uomorders.rejection']" type="danger"
                  @click="editstatus(id, 'rejection')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Rejection</el-button>
                <el-button plain v-permission="['uomorders.auditing']" type="primary"
                  @click="editstatus(id, 'approved')" :disabled="isapproved"
                  v-if="formData.status =='pending' && isdiable">Auditing</el-button>
                <el-button plain type="default" @click="close()"
                  v-if="formData.status =='approved' || formData.status =='voided' || formData.status =='rejection'">Back</el-button>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>


    <div class="form" id="cadd" @click="isgoprolist = false">
      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="190px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Order Number" prop="ordernumber" style="width:490px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Create Date" prop="created_at" style="width:460px">
              <el-date-picker v-model="formData.addtime" type="date" style="width:300px" value-format="yyyy-MM-dd"
                @input="handleDateChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Staff" prop="staff" style="width: 460px;">
              <el-select v-model="formData.staff" placeholder="Select Staff" style="width:300px">
                <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Out Warehouse" prop="warehouse_id" style="width: 460px;">
              <el-select v-model="formData.warehouse_id" placeholder="Select Warehouse" style="width:300px"
                @change="changeoutwar" filterable>
                <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="In Warehouse" prop="warehouse" style="width: 460px;">
              <el-select v-model="formData.inwarehouse_id" placeholder="Select Warehouse" style="width:300px"
                @change="changeoutwar" filterable>
                <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="formData.uomtype+' Product'" prop="product" style="width: 460px;">
              <el-select v-model="formData.product" placeholder="Select product" style="width:300px"
                @change="changeproductv" filterable>
                <el-option v-for="item in productlist" :key="item.productid" :label="item.name" :value="item.productid">
                </el-option>
              </el-select>


            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item :label="formData.uomtype+' Product SKU'" prop="productsku" style="width: 490px;">
              <el-input v-model="formData.productsku" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="On Hand" prop="onhand" style="width: 490px;">
              <!-- <el-input v-model="formData.onhand" /> -->
              {{formData.batchnumber}}-EX{{formData.expirationdate}}-Onhead：{{formData.onhand}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item :label="formData.uomtype+' QTY'" prop="productqty" style="width: 490px;">
              <el-input v-model="formData.productqty" oninput="value=value.replace(/[^\d.]/g,'')" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="formData.uomtype+' Amount'" prop="amount" style="width: 490px;">
              <el-input v-model="formData.productamount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item :label="formData.uomtype+' Product Unit'" prop="productunit" style="width: 490px;">
              <el-input v-model="formData.productunit" />
            </el-form-item>
          </el-col>
          <el-col :span="11">

            <el-form-item label="Batch Number" prop="batchnumber" style="width: 490px;">
              <el-input v-model="formData.batchnumber" />
            </el-form-item>
            <!--            <el-form-item label="Expiration Date" prop="expirationdate" style="width: 460px;">
              <el-date-picker v-model="formData.expirationdate" type="date" style="width:300px"
                value-format="yyyy-MM-dd" @input="handleDateChange">
              </el-date-picker>
            </el-form-item> -->

          </el-col>
        </el-row>
        <!--        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="batchnumber" prop="batchnumber" style="width: 460px;">
              <el-select v-model="formData.batchnumber" placeholder="Select batchnumber" @change="changeProducta"
                style="width:300px">
                <el-option v-for="item in vatchnumberlist" :key="item.batchnumber" :label="item.batchnumber"
                  :value="item.batchnumber">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">

          </el-col>
        </el-row> -->

        <el-row :gutter="20">
          <el-col :span="11">

          </el-col>
          <el-col :span="11">
            <el-form-item label="Expiration Date" prop="expirationdate" style="width: 460px;">
              <el-date-picker v-model="formData.expirationdate" type="date" style="width:300px"
                value-format="yyyy-MM-dd" @input="handleDateChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="cadd">

          <el-table ref="multipleTable" :data="formData.procureditem" prop="procureditem"
            :cell-style="{'text-align':'center'}" :summary-method="getSummaries" show-summary
            :header-cell-style="{'text-align':'center'}" border
            v-if="formData.procureditem && formData.procureditem.length > 0">
            <el-table-column label="NO" prop="" width="60">
              <template slot-scope="scope">
                <span>{{scope.$index+1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="ProductName" prop="status" min-width="150">
              <template slot-scope="scope">
                <el-input ref="inputRefs" v-model="scope.row.productname"
                  @input="onChangeproductname(scope.row.productname,scope.$index,$event)" :rows="3"
                  type="textarea"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="SKU" min-width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sku" @input="onChangeproductsku(scope.row.sku, scope.$index, $event)"
                  :rows="3" type="textarea"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="On Hand QTY" width="120">
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.availableqty" disabled></el-input> -->
                {{ scope.row.availableqty }}
              </template>
            </el-table-column>

            <el-table-column label="QTY" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.qty" type="text" oninput="value=value.replace(/[^\d.]/g,'')" />
              </template>
            </el-table-column>

            <el-table-column label="Unit" width="120">
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.unit" disabled></el-input> -->
                {{ scope.row.unit }}
              </template>
            </el-table-column>

            <el-table-column label="Cost Price" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.costprice" type="text" oninput="value=value.replace(/[^\d.]/g,'')" />
              </template>
            </el-table-column>

            <el-table-column label="Cost Total" width="120">
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.costamount=scope.row.qty*scope.row.costprice" type="text" disabled /> -->
                {{ (scope.row.costamount=scope.row.qty*scope.row.costprice).toFixed(2) }}
              </template>
            </el-table-column>

            <el-table-column label="Batch Number" width="330px">
              <template slot-scope="scope">

                <div style="white-space: pre-wrap;width: 100%;">
                  <el-select v-if="formData.uomtype=='Assembly'" v-model="scope.row.batchnumber"
                    style="white-space: pre-wrap;width: 300px">
                    <el-option :label="itemLabel(scope.row)" :value="scope.row.batchnumber" class="multiline-option"
                      style="white-space: pre-wrap;width: 300px">
                    </el-option>
                  </el-select>
                  <el-input v-if="formData.uomtype=='Disassembly'" v-model="scope.row.batchnumber" type="text" />
                </div>
              </template>
            </el-table-column>

            <el-table-column label="Expiration Date" width="160" v-if="formData.uomtype=='Disassembly'">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.expirationdate" type="date" value-format="yyyy-MM-dd"
                  style="width: 130px;">
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column label="Certificates" width="180">
              <template slot-scope="scope">
                <div v-if="isdiable" style="position: relative;">
                  <a v-if="scope.row.certificates" style="font-size: 12px;" :href="scope.row.certificates"
                    target="_blank"><img src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                  </a>
                  <i v-else class="el-icon-upload"> upload files </i>
                </div>


                <div v-else @mouseenter="showButton(scope.$index)" @mouseleave="hideButton(scope.$index)"
                  style="position: relative;">
                  <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                    :on-change="changeAvatar" :auto-upload="true" :http-request="getUploadHandler(scope.$index)"
                    name="file" :limit="1">
                    <img v-if="scope.row.certificates" src="../../../assets/pdf.png" style="width: 40px;height: 40px" />
                    <i v-else class="el-icon-upload"> upload files </i>
                  </el-upload>

                  <div v-if="scope.row.certificates && hoveredIndex === scope.$index">
                    <a style="font-size: 12px;" :href="scope.row.certificates" target="_blank">view</a>
                    <span style="font-size: 12px;margin-left: 5px; color: red;"
                      @click="delcart(scope.$index)">del</span>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="Note" min-width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.note" :rows="3" type="textarea"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
              <template slot-scope="scope">
                <el-button plain v-permission="['uomorders.destroy']" type="danger" @click="removeItem(scope.row)"
                  size="mini">delete</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--          <div style="text-align: center; font-weight: bold;">
            <span>Total QTY: {{ totalqty }}</span>
            <span> | Total Cost Total: {{ totalamount.toFixed(2) }}</span>
          </div>

 -->

          <el-table :data="tableDatav" size="small" stripe border style="width: 100%;display: none;" class="tableDatav">
            <el-table-column label="NO" prop="" width="60">
              <template slot-scope="scope">
                <span>Total</span>
              </template>
            </el-table-column>
            <el-table-column label="ProductName" prop="status" min-width="150">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="SKU" min-width="150">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="On Hand QTY" width="120">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="QTY" width="120">
              <template slot-scope="scope">
                {{totalqty}}
              </template>
            </el-table-column>

            <el-table-column label="Unit" width="120">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Cost Price" width="120">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Cost Total" width="120">
              <template slot-scope="scope">
                {{totalamount.toFixed(2)}}
              </template>
            </el-table-column>

            <el-table-column label="Batch Number" width="180">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Expiration Date" width="160">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Certificates" width="180">
              <template slot-scope="scope">

              </template>
            </el-table-column>

            <el-table-column label="Note" min-width="150">
              <template slot-scope="scope">

              </template>
            </el-table-column>
            <el-table-column label="Actions" width="110" v-if="isNew || (isEdit && !isdiable)">
              <template slot-scope="scope">

              </template>
            </el-table-column>
          </el-table>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-left: 170px;" v-if="isNew || (isEdit && !isdiable)">
        <el-button type="primary" @click="addItem" :disabled="isdiable">Add Product</el-button>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isubmit">Submit</el-button>
      </div>
    </div>

    <div class="form plt" v-if="isgoprolist" :style="{ 'top': topx }">
      <el-button @click="isgoprolist = false" size="mini"
        style="position: absolute;right: 20px;top: 20px;z-index: 999;height: 40px;color: red;">X</el-button>
      <div class="table">
        <el-table :data="tableData" size="small" stripe border @row-click="handleRowClick" style="width: 100%"
          height="320">
          <el-table-column prop="name" label="Name" width="120" align="center" />
          <el-table-column label="Spec" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="quantity" min-width="100" />
          <el-table-column prop="packaging" label="Packaging" min-width="100" />
          <el-table-column prop="price" label="Price(S$)" width="100" />
          <el-table-column prop="batchnumber" label="Batch Number" width="160" />
          <el-table-column prop="availableqty" label="Available qty" width="140" />
          <!-- <el-table-column label="Actions" width="200">
            <template slot-scope="scope">
              <el-button plain @click="selectadd(scope.row)">select</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- <div slot="footer" class="dialog-footer" style="margin-left: 50%;margin-top: 10px;">
          <el-button @click="isgoprolist=false" size="mini">close</el-button>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index,
    show,
    update,
    store
  } from "@/api/uomorder";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    index as skushow
  } from "@/api/suppersku";
  import {
    index as prolist
  } from "@/api/product";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as superindex
  } from "@/api/supplier";
  import {
    index as prowarlist
  } from "@/api/inventory";
  export default {
    name: "uomorderadd",
    mixins: [CURD],
    data() {
      return {
        price: 0,
        vatchnumberlist: [],
        productlist: [],
        isapproved: false,
        hoveredIndex: null,
        isubmit: false,
        rowIndex: 0,
        x: 0,
        y: 0,
        topx: '60%',
        isgoprolist: false,
        isdiable: true,
        staff: [{
          id: "KW",
          name: "KW",
        }],
        currency: [{
          id: 1,
          name: "SGD",
        }, {
          id: 2,
          name: "USD",
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          staff: "KW",
          procureditem: [],
        },
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
        module: "uomorder",
        newTitle: "New uomorder",
        editTitle: "Edit uomorder",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        suppliers: [],
        warehouse: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        searchForm: {

        },
        inputElements: []
      };
    },
    mounted() {
      this.$once('hook:beforeDestroy', () => {
        this.$emit('destroy');
      });
    },
    watch: {
      'formData.procureditem': {
        handler() {
          //this.updateInputElements();
        },
        deep: true
      }
    },
    computed: {
      totalqty() {
        if (this.formData.procureditem) {
          const totalPrice = this.formData.procureditem.reduce((total, item) => total + parseFloat(item
            .qty), 0);
          return totalPrice ? totalPrice : 0
        }
      },
      totalamount() {
        if (this.formData.procureditem) {
          const amount = this.formData.procureditem.reduce((total, item) => total + parseFloat(item.costamount), 0);
          return amount ? amount : 0
        }
      },
    },
    async created() {
      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        const {
          data
        } = await show(this.id);
        this.formData = data;
        var iscgid = 0;
        if (this.formData.uomtype == "Assembly") {
          //组装
          iscgid = this.formData.warehouse_id
        }
        if (this.formData.uomtype == "Disassembly") {
          iscgid = this.formData.inwarehouse_id
          //拆分
        }
        this.productlist = []
        prowarlist(1, 10000, {
          warehouse_id: iscgid,
          type: 2,
        }).then(res => {
          if (res.data.length > 0) {
            this.formData.product = parseInt(this.formData.product)
          }
          this.productlist = res.data
          if (res.data.length > 0) {
            this.formData.product = parseInt(this.formData.product)
          }
        });



      } else {
        this.formData.uomtype = 'Assembly'
        this.isNew = true
        this.formData.status = "pending"
        this.isdiable = false
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.formData.ordernumber = "SO" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
        this.formData.addtime = `${year}-${month}-${day}`
        this.addItem()
        this.$nextTick(() => {
          const inputElement = document.querySelector(`.el-table__row input:nth-child(${1})`);
          if (inputElement) {
            if (inputElement) {
              const inputRect = inputElement.getBoundingClientRect();
              this.y = inputRect.left
              this.x = inputRect.top - 500
              console.log('Input coordinates:', this.x, this.y);
            }
          }
        });
      }
      try {
        const {
          data
        } = await superindex(1, 100);
        this.suppliers = data;
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }
      try {
        const {
          data
        } = await warehouselist(1, 100);
        this.warehouse = data;

        console.log(data, "warehouse")

      } catch (error) {
        console.error('Failed to fetch warehouse', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.staff = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
    },
    methods: {
      itemLabel(item) {
        return item.batchnumber + '--EX' + item.expirationdate + '-QTY：' + item.availableqty;
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = 'Total';
            return;
          }
          if (index === 4) {
            const totalQuantity = data.reduce((sum, row) => sum + parseFloat(row.qty), 0);
            sums[index] = totalQuantity ? totalQuantity : 0;
          } else if (index === 7) {
            const totalWeight = data.reduce((sum, row) => sum + parseFloat(row.costamount), 0);
            sums[index] = totalWeight ? totalWeight : 0;
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      handleRowClick(row) {
        this.selectadd(row);
      },
      handleDateChange() {
        this.$forceUpdate()
      },
      showButton(index) {
        if (this.isdiable || this.isapproved) {
          return
        }
        this.hoveredIndex = index; // 设置当前鼠标悬停的行的索引
      },
      hideButton(index) {
        if (this.isdiable || this.isapproved) {
          return
        }
        if (this.hoveredIndex === index) {
          this.hoveredIndex = null; // 清除当前鼠标悬停的行的索引
        }
        // 注意：这里其实不需要传入 index，因为 mouseleave 事件已经足够判断鼠标离开了当前元素
        // 但为了保持与 showButton 方法参数的一致性，这里还是传入了 index（尽管未使用）
      },
      delcart(index) {
        this.formData.procureditem[index].certificates = null
      },
      getUploadHandler(index) {
        // 返回一个函数，该函数将作为 http-request 的处理器
        return (options) => {
          // 在这里，我们可以安全地使用 index，因为它是在这个闭包中捕获的
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      godisable() {
        this.isdiable = !this.isdiable
      },
      addItem() { //增加行
        this.xiabiao += 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: "",
          sku: "",
          batbalancer: "",
          availableqty: "",
          qty: "",
          unit: "",
          costprice: "",
          costamount: "",
          saleprice: "",
          expirationdate: "",
          certificates: "",
          batchnumber: "",
          note: "",
          product_id: ""
        });
      },
      removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      async editstatus(id, statusdata) {
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?",
            "prompt", {
              confirmButtonText: "Confirm",
              cancelButtonText: "Cancel",
              type: "warning"
            });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true

          // 刷新当前页
          const {
            data
          } = await show(this.id);
          this.formData = data;
          if (this.formData.status == "approved") {
            this.isapproved = true
          }
          if (this.formData.status == "rejection") {
            this.isapproved = false
            this.isdiable = true
            this.formData.status == "rejection"
          }
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
      selectadd(row) {
        if (row) {
          // skushow(1, 1, {
          //   product_id: row.id
          // }).then(res => {
          //   if (res.data) {
          //     //this.formData.procureditem[this.tindex].suppliesku = res.data[0].csku
          //   }
          // });
          this.formData.procureditem[this.tindex].product_id = row.id
          this.formData.procureditem[this.tindex].productname = row.name
          this.formData.procureditem[this.tindex].sku = row.sku
          this.formData.procureditem[this.tindex].unit = row.uom_sku
          this.formData.procureditem[this.tindex].saleprice = row.price
          this.formData.procureditem[this.tindex].costprice = row.costprice
          this.formData.procureditem[this.tindex].batchnumberlist = row.batchnumberlist
          this.formData.procureditem[this.tindex].batchnumber = row.batchnumber
          this.formData.procureditem[this.tindex].availableqty = row.quantity
          this.formData.procureditem[this.tindex].qty = row.quantity

          this.isgoprolist = false;
        }
      },
      changeProduct(index, event) {
        for (var i = 0; i < this.formData.procureditem[index].batchnumberlist.length; i++) {
          var tm = this.formData.procureditem[index].batchnumberlist[i].batchnumber
          if (tm == this.formData.procureditem[index].batchnumber) {
            this.formData.procureditem[index].onhand = this.formData.procureditem[index].batchnumberlist[i].quantity
            break;
          }
        }
      },
      changeProducta(value) {
        var selba = this.vatchnumberlist.find(item => item.batchnumber === value);
        if (selba) {
          this.formData.expirationdate = selba.expirationdate
          this.price = selba.costprice
        }
        this.$forceUpdate()
      },
      onChangeproductsku(sku, index, event) {
        var iscgid = 0;
        if (this.formData.uomtype == "Assembly") {
          //组装
          iscgid = this.formData.warehouse_id
        }
        if (this.formData.uomtype == "Disassembly") {
          iscgid = this.formData.inwarehouse_id
          //拆分
        }
        if (iscgid) {
          this.$nextTick(() => {
            this.topx = this.x + "px";
            console.log('Input coordinates:', this.x, this.y);
          });
          if (sku) {
            this.tindex = index
            prowarlist(1, 10000, {
              sku: sku,
              warehouse_id: iscgid
            }).then(res => {
              this.tableData = res.data
              this.isgoprolist = true;
            });
          }
        } else {
          if (this.formData.uomtype == "Assembly") {
            //组装
            this.$message({
              type: "info",
              message: "Please select OUT Warehouse"
            });
          }
          if (this.formData.uomtype == "Disassembly") {
            this.$message({
              type: "info",
              message: "Please select IN Warehouse"
            });
            //拆分
          }
        }
      },
      onChangeproductname(proname, index, event) {
        var iscgid = 0;
        if (this.formData.uomtype == "Assembly") {
          //组装
          iscgid = this.formData.warehouse_id
        }
        if (this.formData.uomtype == "Disassembly") {
          iscgid = this.formData.inwarehouse_id
          //拆分
        }
        if (iscgid) {
          this.$nextTick(() => {
            this.topx = this.x + "px";
            console.log('Input coordinates:', this.x, this.y);
          });
          if (proname) {
            this.tindex = index
            prowarlist(1, 10000, {
              name: proname,
              warehouse_id: iscgid
            }).then(res => {
              this.tableData = res.data
              this.isgoprolist = true;
            });
          }
        } else {
          if (this.formData.uomtype == "Assembly") {
            //组装
            this.$message({
              type: "info",
              message: "Please select OUT Warehouse"
            });
          }
          if (this.formData.uomtype == "Disassembly") {
            this.$message({
              type: "info",
              message: "Please select IN Warehouse"
            });
            //拆分
          }
        }
      },
      checkDataAndGetPosition(inputElement) {
        if (inputElement.value === '') {
          setTimeout(() => {
            this.checkDataAndGetPosition(inputElement);
          }, 1000); // 等待1秒后再次尝试获取数据
        } else {
          const inputRect = inputElement.getBoundingClientRect();
          const inputCoordinates = {
            x: inputRect.left,
            y: inputRect.top
          };
          console.log('Input coordinates:', inputCoordinates);
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      changeoutwar() {
        var iscgid = 0;
        if (this.formData.uomtype == "Assembly") {
          //组装
          iscgid = this.formData.warehouse_id
        }
        if (this.formData.uomtype == "Disassembly") {
          iscgid = this.formData.inwarehouse_id
          //拆分
        }
        this.productlist = []
        prowarlist(1, 10000, {
          warehouse_id: iscgid,
          type: 2
        }).then(res => {
          this.productlist = res.data
          if (res.data.length > 0) {
            this.formData.product = res.data[0].productid
            this.changeproductv(res.data[0].productid)
          }
        });
      },
      changeproductv(value) {
        console.log(value, "value产品id")
        const selectedTerm = this.productlist.find(item => item.productid === value);
        if (selectedTerm) {
          this.formData.productunit = selectedTerm.unit
          this.vatchnumberlist = selectedTerm.batchnumberlist
          this.formData.productsku = selectedTerm.sku
          this.formData.onhand = selectedTerm.onhead
          //this.price = selectedTerm.costprice
          if (this.vatchnumberlist.length > 0) {
            // this.formData.expirationdate = this.vatchnumberlist[0].expirationdate
            // this.formData.batchnumber = this.vatchnumberlist[0].batchnumber
            this.price = this.vatchnumberlist[0].costprice
            this.$set(this.formData, 'batchnumber', this.vatchnumberlist[0].batchnumber || '')
            this.$set(this.formData, 'expirationdate', this.vatchnumberlist[0].expirationdate || '')
            this.$nextTick(() => {
              this.$forceUpdate()
            })
            console.log(this.vatchnumberlist[0].costprice, "this.vatchnumberlist[0].costprice")
          }
        }
        this.$forceUpdate()
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.isubmit = true



              if (!this.formData.warehouse_id) {
                this.$message.error("Please add a outwarehouse");
                this.isubmit = false
                return false
              }
              if (!this.formData.inwarehouse_id) {
                this.$message.error("Please add a inwarehouse");
                this.isubmit = false
                return false
              }

              // if (this.formData.warehouse_id == this.formData.inwarehouse_id) {
              //   this.$message.error("Please select a different warehouse.");
              //   this.isubmit = false
              //   return false
              // }

              if (!this.formData.product) {
                this.$message.error("Please add a product");
                this.isubmit = false
                return false
              }
              if (!this.formData.productsku) {
                this.$message.error("Please add a productsku");
                this.isubmit = false
                return false
              }
              if (!this.formData.onhand) {
                this.$message.error("Please add a onhand");
                this.isubmit = false
                return false
              }
              if (!this.formData.productqty) {
                this.$message.error("Please add a productqty");
                this.isubmit = false
                return false
              }
              if (!this.formData.productamount) {
                this.$message.error("Please add a productamount");
                this.isubmit = false
                return false
              }
              if (!this.formData.productunit) {
                this.$message.error("Please add a inwarehouse");
                this.isubmit = false
                return false
              }
              // if (!this.formData.expirationdate) {
              //   this.$message.error("Please add a expirationdate");
              //   this.isubmit = false
              //   return false
              // }
              if (!this.formData.batchnumber) {
                this.$message.error("Please add a batchnumber");
                this.isubmit = false
                return false
              }

              // if (!this.formData.product) {
              //   this.$message.error("Please add a product");
              //   this.isubmit = false
              //   return false
              // }
              // if (!this.formData.productsku) {
              //   this.$message.error("Please add a productsku");
              //   this.isubmit = false
              //   return false
              // }

              // prolist(1, 1, {
              //   sku: this.formData.productsku,
              //   pnamesku: this.formData.product,
              // }).then(res => {
              //   console.log(res, "ppppppppp")
              //   if (res.data.length <= 0) {
              //     this.$message.error("Please fill in the correct product and SKU");
              //     this.isubmit = false
              //     return false
              //   }
              // });


              for (var i = 0; i < this.formData.procureditem.length; i++) {
                var tm = this.formData.procureditem[i].productname
                if (tm == "") {
                  this.$message.error("Please add a product data");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].qty
                if (tm == "") {
                  this.$message.error("Please add a product qty");
                  this.isubmit = false
                  return false
                }
                var tm = this.formData.procureditem[i].costprice
                if (tm == "") {
                  this.$message.error("Please add a product costprice");
                  this.isubmit = false
                  return false
                }
                // var tm = this.formData.procureditem[i].expirationdate
                // if (tm == "") {
                //   this.$message.error("Please add a product expirationdate");
                //   this.isubmit = false
                //   return false
                // }
                var tm = this.formData.procureditem[i].batchnumber
                if (tm == "") {
                  this.$message.error("Please add a product batchnumber");
                  this.isubmit = false
                  return false
                }
              }

              this.formData.totalqty = this.totalqty
              this.formData.totalamount = this.totalamount

              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/Inventory/uomorder'
                  });
                }, 1000);

              }
              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem.length > 0) {

                } else {
                  this.$message.error("Please add a product");
                  this.isubmit = false
                  return false
                }

                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                if (info1) {
                  if (info1.status_code = 201) {
                    this.$message.success("Add successfully");
                    setTimeout(() => {
                      this.$store.dispatch('tagsView/delView', this.$route);
                      this.$router.push({
                        path: '/uomorder/edituomorder',
                        query: {
                          id: info1.info
                        }
                      })
                    }, 1000);
                  } else {
                    this.isubmit = false
                    this.$message.error(
                      "Data verification error");
                    return false;
                  }
                }
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
              this.isubmit = false
            } catch (error) {
              let result = error.response.data;
              this.isubmit = false
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      close() {
        this.$router.push({
          path: '/Inventory/uomorder'
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              //this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        console.log("sssssssssssssssssss")
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>